<?php

declare(strict_types=1);

namespace App\Controller\Mini\V2\Users;

use App\Controller\Mini\V2\Controllers;
use App\Services\Message\Sms;
use App\Services\Users\Payer as PayerServices;
use App\Request\Users\Payer as PayerRequest;
use Psr\Http\Message\ResponseInterface;
use function Hyperf\Translation\__;

/**
 * Class Payer
 * @author zx
 * @package App\Controller\Mini\V2\Users
 */
class Payer extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = PayerRequest::class;

    public function __construct(
        PayerServices $payerServices
    )
    {
        parent::__construct();

        $this->services = $payerServices;
    }

    /**
     * 分页
     * @return ResponseInterface
     * @throws \Throwable
     */
    public function page():ResponseInterface
    {
        $query = $this->query();

        [$field, $order] = $this->orderMap('', [], 'is_default');
        $page = $this->services
            ->search($query)
            ->orderBy($field, $order)
            ->simplePaginate($this->getLimit());

        return success(compact('page'));
    }

    /**
     * 新增
     * @param Sms $smsServices
     * @return ResponseInterface
     */
    public function save(Sms $smsServices):ResponseInterface
    {
        $input = $this->input(['name', 'id_card', 'mobile', 'code', 'front_img', 'back_img', 'hand_front_img', 'hand_back_img', 'is_default' => 0]);

        if (!$smsServices->verification($input['mobile'], $input['code'])) {
            return failed(__('message.sms.code.failed'));
        }

        /** @var \App\Model\Users\Payer $model */
        $model = $this->services->auth($input);

        return stored([
            'id' => $model->id
        ]);
    }

    /**
     * 设置为默认
     * @param int $id
     * @return ResponseInterface
     */
    public function update(int $id):ResponseInterface
    {
        $model = $this->services->findOrFail($id);

        $model->fill(['is_default' => 1])->save();

        return updated();
    }

    /**
     * 发送验证码
     * @param Sms $smsServices
     * @return ResponseInterface
     */
    public function code(Sms $smsServices):ResponseInterface
    {
        $input = $this->input(['mobile']);
        $smsServices->code($input['mobile']);

        return success();
    }
}
